﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Text;

namespace WebUI.Util
{
    public class XmlHelper
    {
        public static void SerializeToXml<T>(T objectToSerialize, string filePath)
        {
            TextWriter textWriter = null;

            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                textWriter = new StreamWriter(filePath);
                serializer.Serialize(textWriter, objectToSerialize);
            }
            catch
            {
                throw new Exception("Cannot write the XML file");
            }
            finally
            {
                if (textWriter != null)
                    textWriter.Close();
                }
        }

        public static string SerializeToXML<T>(T value)
        {
            if (value == null) return null;

            XmlSerializer serializer = new XmlSerializer(typeof(T));
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Encoding = new UnicodeEncoding(false, false); // no BOM in a .NET string
            settings.Indent = false;
            settings.OmitXmlDeclaration = false;

            using (StringWriter textWriter = new StringWriter())
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
                {
                    serializer.Serialize(xmlWriter, value);
                }
                return textWriter.ToString();
            }
        }

        public static T DeserializeFromXml<T>(string filePath)
        {
            using (NetworkShareAccesser.Access(filePath.Substring(2, 15), @"lac", "lac_bra_ftools", "Ferrari3k10"))
            {
                StreamReader textReader = null;

                try
                {
                    XmlSerializer deserializer = new XmlSerializer(typeof(T));
                    textReader = new StreamReader(filePath);
                    var objectDeserialized = (T)deserializer.Deserialize(textReader);
                    return objectDeserialized;
                }
                catch
                {
                    throw new FileLoadException("Cannot load the XML file");
                }

                finally
                {

                    if (textReader != null)
                        textReader.Close();
                }
            }
        }
    }
}